import { MyPlane } from "./myPlane";
export class GameEngine {
  public el: HTMLDivElement;
  static instanceObj: GameEngine;
  constructor() {
    this.el = document.querySelector("#main_body") as HTMLDivElement;
    this.init();
  }
  static instance() {
    if (GameEngine.instanceObj == null) {
      GameEngine.instanceObj = new GameEngine();
    }
    return GameEngine.instanceObj;
  }

  init() {
    this.el.addEventListener("click", (e: Event) => {
      let target: HTMLElement = e.target as HTMLElement;
      if (target.nodeName != "LI") return;
      let level = target.getAttribute("value"); //获得有点的难度值
      //开始游戏
      this.start();
    });
  }
  //开始游戏
  start() {
    this.el.innerHTML = "";
    this.loading(() => {
      this.el.innerHTML = "";
      MyPlane.instance();
      this.controller();
    });
  }
  //加载进度条
  loading(callback: Function) {
    let logo: HTMLDivElement = document.createElement("div");
    logo.classList.add("logo");
    this.el.appendChild(logo);

    let loading: HTMLDivElement = document.createElement("div");
    loading.className = "loading";
    this.el.appendChild(loading);

    let lodingIndex = 0;
    let timer = setInterval(() => {
      lodingIndex++;
      loading.style.backgroundImage = `url(/src/assets/images/loading${
        (lodingIndex % 3) + 1
      }.png)`;

      if (lodingIndex >= 5) {
        clearInterval(timer);
        if (callback && typeof callback == "function") {
          callback();
        }
      }
    }, 100);
  }
  //控制战机左右移动
  controller() {
    window.addEventListener("keydown", (e: KeyboardEvent) => {
      if (e.keyCode == 37) {
        //新的位置=当前位置+步长
        let mX=MyPlane.instance().el.offsetLeft-20;
        if (mX<=0) {
          mX=0;
        }
       MyPlane.instance().el.style.left=mX+'px';
      }
      if (e.keyCode == 39) {
        let mX=MyPlane.instance().el.offsetLeft+20;
        let maxWidth=GameEngine.instance().el.offsetWidth-MyPlane.instance().el.offsetWidth;
        if (mX>maxWidth) {
          mX=maxWidth
        }
         MyPlane.instance().el.style.left=mX+'px'
      }
    });
  }
}
